//
//  MAAnPaiJieSongController.m
//  meiang_edu
//
//  Created by hfcb on 2018/9/14.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MAAnPaiJieSongController.h"
#import <FSCalendar.h>
#import <EventKit/EventKit.h>
#import "MAStaffModel.h"
#import "MAPopView.h"
#import <zhPopupController.h>
#import "MAPopViewCell.h"
#import "NSDate+Js.h"
#import "MAJiGouModel.h"

@interface MAAnPaiJieSongController ()<FSCalendarDelegate, FSCalendarDataSource>
@property (weak, nonatomic) IBOutlet UIView *fsView;
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *subLabel;
@property (weak, nonatomic) IBOutlet UILabel *jsNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *dayCountLabel;

@property (weak, nonatomic) FSCalendar *calendar;
@property (strong, nonatomic) NSCalendar *chineseCalendar;
@property (strong, nonatomic) NSCalendar *gregorian;
@property (strong, nonatomic) NSArray<NSString *> *lunarChars;
@property (strong, nonatomic) NSArray<EKEvent *> *events;

@property (strong, nonatomic) NSDateFormatter *dateFormatter;

/** babyModels */
@property(nonatomic,strong) NSMutableArray *babyModels;

/** popView */
@property(nonatomic,strong) MAPopView *popView;

/** beginDate */
@property(nonatomic,copy) NSString *beginDate;

/** endDate */
@property(nonatomic,copy) NSString *endDate;

/** minDate */
@property(nonatomic,copy) NSString *minDate;

/** maxDate */
@property(nonatomic,copy) NSString *maxDate;

/** dataArr */
@property(nonatomic,strong) NSMutableArray *dataArr;

@end

@implementation MAAnPaiJieSongController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupBasic];

    [self setupFS];
    
    [self loadBabyData];
    
}

- (void)setupBasic {
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 4)];
    self.tableView.tableFooterView = [UIView new];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(save) image:@"savebutton_logo" highImage:@"savebutton_logo"];
    self.title = @"安排接送";
    
    self.gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    self.beginDate = [NSDate _wj_stringWithDate:[[NSDate date] wj_beginDayOfMonth] format:@"yyyy-MM-dd"];
    self.endDate = [NSDate _wj_stringWithDate:[[NSDate date] wj_lastDayOfMonth] format:@"yyyy-MM-dd"];
    self.minDate = self.beginDate;
    self.maxDate = self.endDate;
}

- (void)setupFS {
    FSCalendar *calendar = [[FSCalendar alloc] initWithFrame:self.fsView.bounds];
    calendar.dataSource = self;
    calendar.delegate = self;
    calendar.backgroundColor = [UIColor whiteColor];
    calendar.width = SCREEN_WIDTH - 8;
    calendar.height = 280;
    calendar.x = 0;
    calendar.y = 0;
    calendar.allowsMultipleSelection = YES;
    calendar.appearance.headerMinimumDissolvedAlpha = 0.0;
    calendar.appearance.borderSelectionColor = PROJECT_DEFAULT_COLOR;
    calendar.appearance.selectionColor = PROJECT_DEFAULT_COLOR;
    calendar.appearance.headerDateFormat = @"yyyy年MM月";
    calendar.scrollEnabled = NO;
    [self.fsView insertSubview:calendar atIndex:0];
    self.calendar = calendar;
    self.chineseCalendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese];
    self.lunarChars = @[@"初一",@"初二",@"初三",@"初四",@"初五",@"初六",@"初七",@"初八",@"初九",@"初十",@"十一",@"十二",@"十三",@"十四",@"十五",@"十六",@"十七",@"十八",@"十九",@"二十",@"廿一",@"廿二",@"廿三",@"廿四",@"廿五",@"廿六",@"廿七",@"廿八",@"廿九",@"三十"];
    __weak typeof(self) weakSelf = self;
    EKEventStore *store = [[EKEventStore alloc] init];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if(granted) {
            self.dateFormatter = [[NSDateFormatter alloc] init];
            self.dateFormatter.dateFormat = @"yyyy-MM-dd";
            
            NSDate *startDate = [self.dateFormatter dateFromString:@"2000-01-01"]; // 开始日期
            NSDate *endDate = [self.dateFormatter dateFromString:@"2021-04-10"]; // 截止日期
            NSPredicate *fetchCalendarEvents = [store predicateForEventsWithStartDate:startDate endDate:endDate calendars:nil];
            NSArray<EKEvent *> *eventList = [store eventsMatchingPredicate:fetchCalendarEvents];
            NSArray<EKEvent *> *events = [eventList filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(EKEvent * _Nullable event, NSDictionary<NSString *,id> * _Nullable bindings) {
                return event.calendar.subscribed;
            }]];
            weakSelf.events = events;
        }
    }];
}


- (IBAction)preBtnDidClick:(UIButton *)sender {
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *previousMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:-1 toDate:currentMonth options:0];
    [self.calendar setCurrentPage:previousMonth animated:YES];
    
    self.beginDate = [NSDate _wj_stringWithDate:[previousMonth wj_beginDayOfMonth] format:@"yyyy-MM-dd"];
    self.endDate = [NSDate _wj_stringWithDate:[previousMonth wj_lastDayOfMonth] format:@"yyyy-MM-dd"];
    
    NSDate *date = [NSDate _wj_dateWithString:self.minDate format:@"yyyy-MM-dd"];
    NSDate *min = [date earlierDate:[previousMonth wj_beginDayOfMonth]];
    self.minDate = [NSDate _wj_stringWithDate:min format:@"yyyy-MM-dd"];
    [self loadJieSongData];
}

- (IBAction)nextBtnDidClick:(UIButton *)sender {
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *nextMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:currentMonth options:0];
    [self.calendar setCurrentPage:nextMonth animated:YES];
    
    self.beginDate = [NSDate _wj_stringWithDate:[nextMonth wj_beginDayOfMonth] format:@"yyyy-MM-dd"];
    self.endDate = [NSDate _wj_stringWithDate:[nextMonth wj_lastDayOfMonth] format:@"yyyy-MM-dd"];
    NSDate *date = [NSDate _wj_dateWithString:self.maxDate format:@"yyyy-MM-dd"];
    NSDate *max = [date laterDate:[nextMonth wj_lastDayOfMonth]];
    self.maxDate = [NSDate _wj_stringWithDate:max format:@"yyyy-MM-dd"];
    [self loadJieSongData];
}

- (void)loadBabyData {
    
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    DLog(@"%@",self.title);
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBHTTPRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@?entity_type=familychildbyorg&status=1",BASE_LISTENTITY_LIST,self.jigou_id];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            self.babyModels = [MAStaffModel mj_objectArrayWithKeyValuesArray:dataDict[@"value"]];
            [self bindInfo];
            
            [self loadJieSongData];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
    }];
}

- (void)loadJieSongData {
    if (!self.babyModels.count) {
        [MBManager showBriefAlert:@"没有添加宝宝,还不能安排接送"];
        return;
    }
    MAStaffModel *model = [self.babyModels firstObject];
    
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    DLog(@"%@",self.title);
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBHTTPRequestSerializer;
//        ch_id    孩子ID
//        org_id    家庭组ID
//        us_id    用户ID
//        date_begin    开始日期
//        date_end    结束日期

        request.URLString = [NSString stringWithFormat:@"%@%@?ch_id=%@&org_id=%@&us_id=%@&date_begin=%@&date_end=%@",SENDER_PLANS_LIST,model.ID,model.ID,model.orgkey,self.model.ID,self.beginDate,self.endDate];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            for (NSDictionary *dic in dataDict[@"value"]) {
                if (![self.dataArr containsObject:dic[@"ddate"]]) {
                    [self.dataArr addObject:dic[@"ddate"]];
                    NSDate *date = [NSDate _wj_dateWithString:dic[@"ddate"] format:@"yyyy-MM-dd"];
                    [self.calendar selectDate:date scrollToDate:NO];
                }
            }
            self.dayCountLabel.text = [NSString stringWithFormat:@"%ld天",self.dataArr.count];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
    }];
}

- (void)bindInfo {
    if (self.babyModels.count) {
        MAStaffModel *model = [self.babyModels firstObject];
        [self.iconView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_OSS,model.ps_id]] placeholderImage:[UIImage imageNamed:@"homepage_navigationbar_picture"]];
        self.nameLabel.text = model.cname;
        self.subLabel.text = model.us_type;
        
        self.jsNameLabel.text = self.model.cname;
    }
}

- (void)save {
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    //    "sender": "",//接送人key 临时接送人 客户端生成guid
    //    "ch_key": "",//孩子key
    //    "org_key": "",//机构key
    //    "dates": "",//日期数组
    //    "usname": "",//接送人姓名
    //    "phone": ""//接送人联系电话
    MAStaffModel *model = [self.babyModels firstObject];
    NSMutableDictionary *body = [NSMutableDictionary dictionary];
    body[@"sender"] = self.model.ID;
    body[@"ch_key"] = model.ID;
    body[@"org_key"] = self.jigouModel.ID;
    body[@"dates"] = [self.dataArr mj_JSONString];
    body[@"usname"] = self.model.cname;
    body[@"phone"] = self.model.others;
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:SENDER_PLANS_ADD parameters:nil error:nil];
    
    [req setValue:@"application/text" forHTTPHeaderField:@"Content-Type"];
    
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [MBManager hideAlert];
        if (!error) {
            DLog(@"Reply JSON: %@", responseObject);
            NSInteger msgcode = [responseObject[@"msgcode"] integerValue];
            NSString *message = responseObject[@"message"];
            if (msgcode == 1) {
                [MBManager showBriefAlert:message];
            } else {
                [MBManager showBriefAlert:message];
            }
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            DLog(@"Error: %@, %@, %@", error, response, responseObject);
            [MBManager showBriefAlert:@"网络错误"];
        }
    }] resume];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - FSCalendarDelegate, FSCalendarDataSource
- (NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date
{
    EKEvent *event = [self eventsForDate:date].firstObject;
    if (event) {
        return event.title; // 春分、秋分、儿童节、植树节、国庆节、圣诞节...
    }
    NSInteger day = [self.chineseCalendar component:NSCalendarUnitDay fromDate:date];
    return _lunarChars[day-1]; // 初一、初二、初三...
}

// 某个日期的所有事件
- (NSArray<EKEvent *> *)eventsForDate:(NSDate *)date
{
    NSArray<EKEvent *> *filteredEvents = [self.events filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(EKEvent * _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
        return [evaluatedObject.occurrenceDate isEqualToDate:date];
    }]];
    return filteredEvents;
}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    NSString *select = [date wj_dateStringFormatYMD];
    DLog(@"%@",select);
    if (![self.dataArr containsObject:select]) {
        [self.dataArr addObject:select];
    }
}

- (void)calendar:(FSCalendar *)calendar didDeselectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    NSString *deselect = [date wj_dateStringFormatYMD];
    DLog(@"%@",deselect);
    if ([self.dataArr containsObject:deselect]) {
        [self.dataArr removeObject:deselect];
    }
}

- (BOOL)calendar:(FSCalendar *)calendar shouldSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    return YES;
}

//- (UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance fillSelectionColorForDate:(NSDate *)date
//{
//    return [UIColor redColor];
//}

//- (UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance fillDefaultColorForDate:(NSDate *)date
//{
//    return [UIColor orangeColor];
//}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        self.popView = [MAPopView popView];
        MJWeakSelf;
        self.popView.selectedBlock = ^(MAStaffModel *model) {
            [weakSelf.babyModels removeObject:model];
            [weakSelf.babyModels insertObject:model atIndex:0];
            [weakSelf bindInfo];
            [weakSelf.zh_popupController dismiss];
        };
        self.popView.layer.cornerRadius = 10;
        self.popView.layer.masksToBounds = YES;
        self.popView.height = self.babyModels.count * 40;
        self.popView.myTableView.delegate = self.popView;
        self.popView.myTableView.dataSource = self.popView;
        
        self.zh_popupController = [[zhPopupController alloc] init];
        self.zh_popupController.dismissOnMaskTouched = YES;
        self.zh_popupController.dismissOppositeDirection = YES;
        self.zh_popupController.slideStyle = zhPopupSlideStyleShrinkInOut2;
        [self.zh_popupController presentContentView:self.popView duration:0.35 springAnimated:YES];
        self.popView.models = self.babyModels;
        [self.popView.myTableView reloadData];
    }
}

#pragma mark - getter % setter
- (NSMutableArray *)babyModels {
    if (_babyModels == nil) {
        _babyModels = [NSMutableArray array];
    }
    return _babyModels;
}
- (NSMutableArray *)dataArr {
    if (_dataArr == nil) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}
@end
